﻿using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;

namespace MicroBlog
{
    /// <summary>
    /// 授权处理程序
    /// </summary>
    public class MicroAuthorizationHandler : AuthorizationHandler<MicroRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MicroRequirement requirement)
        {
            var role = context.User.FindFirst(c => c.Type == ClaimTypes.Role && c.Value.Equals(requirement.Roles));

            if (role is null)
            {
                return Task.CompletedTask;
            }

            if (role.Value.Equals(requirement.Roles))
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// 授权要求
    /// </summary>
    public class MicroRequirement : IAuthorizationRequirement
    {
        /// <summary>
        /// 角色
        /// </summary>
        public string Roles { get; set; }
        public MicroRequirement(string role)
        {
            Roles = role;
        }
    }
}
